package com.zjuee.web.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjuee.web.auth.enums.RoleType;
import com.zjuee.web.auth.mapper.RoleMapper;
import com.zjuee.base.bean.Pages;
import com.zjuee.base.bean.response.CommonResultCode;
import com.zjuee.base.dto.common.auth.RoleDto;
import com.zjuee.base.exception.BaseException;
import com.zjuee.base.model.common.auth.Role;
import com.zjuee.base.utils.CommonUtil;
import com.zjuee.service.auth.service.RoleService;
import com.zjuee.service.auth.service.UserRoleService;
import com.zjuee.service.auth.vo.MenuVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 角色服务接口实现类
 *
 * @author wu liang
 * @since 1.0
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleService userRoleService;

//    @Resource
//    private LoginDto loginDto;

    @Override
    public Long add(Role role) {
        role.setName(role.getName().trim());
        //角色编码 - 暂时为空
        role.setRoleCode("");
        // 获取code并校验父节点
        if (role.getParentId() != null && role.getParentId() != 0) {
            Role parentRole = roleMapper.selectById(role.getParentId());
            if (parentRole == null) {
                throw new BaseException(CommonResultCode.ILLEGAL_INPUT, "父节点不存在");
            }
            String levelCode = parentRole.getLevelCode();
            role.setLevelCode(getMaxLevelCode(levelCode));
        } else {
            role.setParentId(2L);
            role.setLevelCode(getMaxLevelCode("001"));
        }

        //资源类型默认都是可修改的，系统预录入的可在数据库中修改其类型
        role.setRoleType(RoleType.user.getValue());
        role.setNodeType((byte)0);
        role.setGmtCreate(new Date());
        role.setGmtModify(new Date());
        //获取当前用户
//        role.setOrgId(loginDto.getOrgId());
//        role.setCreateId(loginDto.getUserId());
//        role.setModifyId(loginDto.getUserId());
        roleMapper.insert(role);

        return role.getId();
    }

    @Override
    public boolean delete(Long id, Long orgId) {
        // 校验id的真实性
        Role role = selectById(id, orgId);
        if (role==null)
            throw new BaseException(CommonResultCode.ILLEGAL_INPUT, "角色不存在");

        // 判断此角色是否已已被分配
        Integer count = userRoleService.findAllUserByRoleId(id);
        if (count!=null && count > 0) {
            throw new BaseException(CommonResultCode.CONSUMER_ERR, "此角色已被分配，无法删除");
        }
        //删除 用户——角色 关联关系
        userRoleService.deleteByRoleId(id);
        //删除角色
        return roleMapper.deleteById(id) > 0;
    }

    @Override
    public boolean update(Role role) {
        Role existRole = selectById(role.getId(),0L);
        if (existRole==null) {
            throw new BaseException(CommonResultCode.CONSUMER_ERR, "角色不存在");
        }

        //设置只允许修改的内容
        existRole.setName(role.getName().trim());
        existRole.setRoleCode(role.getRoleCode());
        existRole.setRemark(role.getRemark());

        existRole.setModifyId(0L);
        existRole.setGmtModify(new Date());
        return roleMapper.updateById(existRole) > 0;
    }

    @Override
    public Role selectById(Long id, Long orgId) {
        LambdaQueryWrapper<Role> queryWrapper = Wrappers.<Role>query().lambda();
        queryWrapper.eq(Role::getId, id).eq(Role::getOrgId, orgId);
        return roleMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Role> selectByParentId(Long parentId, Long validateId) {
        LambdaQueryWrapper<Role> queryWrapper = Wrappers.<Role>query().lambda();
        queryWrapper.eq(Role::getParentId, parentId);
        queryWrapper.select(Role::getId,Role::getParentId,Role::getName);
        return roleMapper.selectList(queryWrapper);
    }

    @Override
    public List<MenuVo> findAllMenu(Long roleId) {
        if (roleId==null) {
            throw new BaseException(CommonResultCode.CONSUMER_ERR, "角色id不能为空");
        }
        //忽略角色的真实性
        List<MenuVo> menus = roleMapper.findAllMenuByRoleId(roleId);
        return CommonUtil.buildTree(menus, MenuVo::getLevelCode, MenuVo::getChildren);
    }

    @Override
    public Page<Role> list(RoleDto roleDto) {
        if (!Optional.ofNullable(roleDto.getPage()).isPresent()) {
            roleDto.setPage(new Pages());
        }
        return roleMapper.selectPage(roleDto.getPage().convert(), fuzzyQuery(roleDto));
    }

    @Override
    public LambdaQueryWrapper<Role> fuzzyQuery(RoleDto roleDto) {
        LambdaQueryWrapper<Role> queryWrapper = Wrappers.<Role>query().lambda();
        Optional.ofNullable(roleDto).ifPresent(dto -> {
            if (StringUtils.isNotBlank(dto.getName())) {
                queryWrapper.like(Role::getName, dto.getName());
            }
            queryWrapper.eq(Role::getParentId,0L);
            queryWrapper.select(Role::getId,Role::getParentId,Role::getName,Role::getOrgId,Role::getRemark,Role::getGmtCreate);
        });
        return queryWrapper;
    }

    //获取下一层 下一个levelCode
    private String getMaxLevelCode(String prefix) {
        prefix = prefix == null ? "" : prefix;
        String levelCodeFormat = prefix + "___";
        String levelStr = roleMapper.getMaxLevelCode(levelCodeFormat);

        if (StringUtils.isBlank(levelStr)) {
            return prefix + "000";
        }

        String codeStr = levelStr.substring(prefix.length());
        int newCode = Integer.parseInt(codeStr) + 1;
        String temp = "000" + newCode;

        return prefix + temp.substring(temp.length() - 3);
    }


}
